package hr.pzrinscak.service;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import hr.pzrinscak.util.StaticUtils;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.MailPreparationException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

public class MailService {

    private final static Logger LOGGER = LoggerFactory.getLogger(MailService.class);

    @Autowired
    private JavaMailSender mailSender;

    private Configuration configuration;

    public void sendEmail(final String address, final String subject, final String emailTemplate) {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(final MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(address);
                message.setFrom(StaticUtils.EMAIL_FROM);
                message.setSubject(subject);
                Map<String, Object> model = new HashMap<String, Object>();
                Template template = configuration.getTemplate(emailTemplate);
                final StringWriter textWriter = new StringWriter();
                try {
                    template.process(model, textWriter);
                } catch (TemplateException e) {
                    throw new MailPreparationException("Greška u procesiranju email template-a.", e);
                }

                message.setText(textWriter.toString(), true);
            }
        };
        try {
            this.mailSender.send(preparator);
        } catch (MailException e) {
            LOGGER.error("Greška u slanju maila na adresu " + address + " .", e );
        }
    }

    @Autowired
    public void setFreeMarkerConfigurer(final FreeMarkerConfigurer freeMarkerConfigurer) {
        this.configuration = freeMarkerConfigurer.getConfiguration();
    }

}
